package com.zhentao.controller;

import com.zhentao.common.Result;
import com.zhentao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 头像上传控制器（本地文件存储）
 */
@RestController
@RequestMapping("/api/avatar")
@CrossOrigin(origins = "*")
public class AvatarUploadController {
    
    @Autowired
    private UserService userService;
    
    @Value("${avatar.upload.path}")
    private String uploadPath;
    
    @Value("${avatar.url.prefix}")
    private String urlPrefix;
    
    /**
     * 上传用户头像（本地文件存储）
     * @param file 图片文件
     * @param userId 用户ID
     * @return 上传结果，包含头像URL
     */
    @PostMapping("/upload")
    public Result<String> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") Long userId) {
        
        System.out.println("=== 接收头像上传请求（本地存储）===");
        System.out.println("用户ID: " + userId);
        System.out.println("文件名: " + file.getOriginalFilename());
        System.out.println("文件大小: " + file.getSize() + " bytes");
        System.out.println("上传路径: " + uploadPath);
        System.out.println("URL前缀: " + urlPrefix);
        
        try {
            // 1. 验证文件
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }
            
            // 2. 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件");
            }
            
            // 3. 验证文件大小（不超过5MB）
            long maxSize = 5 * 1024 * 1024; // 5MB
            if (file.getSize() > maxSize) {
                return Result.error("图片大小不能超过5MB");
            }
            
            // 4. 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = "avatar_" + userId + "_" + System.currentTimeMillis() + suffix;
            System.out.println("生成文件名: " + fileName);
            
            // 5. 确保上传目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                System.out.println("创建上传目录: " + uploadPath + ", 结果: " + created);
            }
            
            // 6. 保存文件到本地
            Path filePath = Paths.get(uploadPath, fileName);
            Files.write(filePath, file.getBytes());
            System.out.println("文件已保存到: " + filePath.toAbsolutePath());
            
            // 7. 生成访问URL
            String avatarUrl = urlPrefix + fileName;
            System.out.println("生成访问URL: " + avatarUrl);
            
            // 8. 更新数据库中的头像URL
            boolean success = userService.updateAvatarUrl(userId, avatarUrl);
            if (!success) {
                System.err.println("❌ 数据库更新失败");
                return Result.error("更新头像失败");
            }
            
            System.out.println("✅ 头像上传成功！");
            return Result.success("头像上传成功", avatarUrl);
            
        } catch (IOException e) {
            System.err.println("❌ 文件保存失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error("文件保存失败: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("❌ 上传失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error("上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户头像URL
     * @param userId 用户ID
     * @return 头像URL
     */
    @GetMapping("/url")
    public Result<String> getAvatarUrl(@RequestParam Long userId) {
        try {
            String avatarUrl = userService.getAvatarUrl(userId);
            return Result.success("获取成功", avatarUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取失败: " + e.getMessage());
        }
    }
}

